<?php
namespace app\admin\controller\edu;
use app\common\controller\Backend;
use think\Controller;
use think\Request;
use think\Session;
use think\facade\Lang;
use fast\Tree;
use fast\Cols;
use fast\Date;
use fast\Random;
use think\cache\Driver\File;
class Classes extends Backend{
		protected $model = null;//模型对象
		protected $columnlist = array();
		public function initialize(){
				parent::initialize();
				$this->model = model('Classes');
				$this->columnarry = Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/module.php','',1);
		}
		public function add(){
				if ($this->request->isPost()){
						$params = $this->request->post("row/a");
						if ($params){
								$fc = new File();
								$this->modelValidate = false;
								if ($this->dataLimit){
										$params[$this->dataLimitField] = $this->auth->id;
								}
								try{
										//是否采用模型验证
										if ($this->modelValidate){
												$name = basename(str_replace('\'', '/', get_class($this->model)));
												$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
												$this->model->validate($validate);
										}
										$params['adminid'] = $this->auth->itemid;
										$modelclasses = \app\common\model\Classes::create($params);
										if ($modelclasses !== false){
												$datacache = array();
												cache('classes'.$modelclasses->itemid,$datacache);
												$this->success();
										}else{
												$this->error($this->model->getError());
										}
								}
								catch (\think\exception\PDOException $e){
										$this->error($e->getMessage());
								}
						}
						$this->error(__('Parameter %s can not be empty', ''));
				}else{
								$schoolid = dsafe($this->request->get('schoolid'));
								$this->view->assign("schoolid",$schoolid);
						$fc = new File();
						return $this->view->fetch();
				}
		}
		public function edit($ids = NULL){
				$row = $this->model->find($ids);
				$row['school'] = model('School')->getSchoolByCache($row['schoolid']);
				$schoolstr = '';
				foreach ($row['school'] as $k => $v) {
						$schoolstr .= $v;
						$schoolstr .= ",";
				}
				$this->view->assign('schoolstr',$schoolstr);
				if(isset($row['catid'])){
						$row['category'] = model('Category')->getCategoryByCache($row['catid']);
				}
				$fc = new File();
				if (!$row){$this->error(__('No Results were found'));}
				$adminIds = $this->getDataLimitAdminIds();
				if (is_array($adminIds)){
						if (!in_array($row[$this->dataLimitField], $adminIds)){
								$this->error(__('You have no permission'));
						}
				}
				if ($this->request->isPost()){
						$params = $this->request->post("row/a");
						if ($params){
								try{
										//是否采用模型验证
										if ($this->modelValidate){
												$name = basename(str_replace('\'', '/', get_class($this->model)));
												$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
												$row->validate($validate);
										}
										$params['adminid'] = $this->auth->itemid;
										$result = $row->allowField(true)->save($params,['itemid' => $ids]);
										if ($result !== false){
												$datacache = array();
												cache('classes'.$ids,$datacache);
												$this->success();
										}
										else{$this->error($row->getError());}
								}
								catch (\think\exception\PDOException $e){
										$this->error($e->getMessage());
								}
						}
						$this->error(__('Parameter %s can not be empty', ''));
				}
				$this->view->assign("row", $row);
				return $this->view->fetch();
		}
		public function editbyschool($schoolid = NULL){
				if ($this->request->isPost()){
						$params = $this->request->post("row/a");
						$row = $this->model->get(['schoolid'=>$params['schoolid']]);
						if ($params){
								try{
										//是否采用模型验证
										if ($this->modelValidate){
												$name = basename(str_replace('\'', '/', get_class($this->model)));
												$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
												$row->validate($validate);
										}
										$params['adminid'] = $this->auth->itemid;
										if($row){
												$result = $row->allowField(true)->save($params,['schoolid' => $params['schoolid']]);
										}else{
												$result = \app\common\model\Classes::create($params);
										}
										if ($result !== false){
												$this->success();
										}else{
												$this->error($row->getError());
										}
								}catch (\think\exception\PDOException $e){
										$this->error($e->getMessage());
								}
						}
						$this->error(__('Parameter %s can not be empty', ''));
				}else{
						$row = $this->model->get(['schoolid'=>$schoolid]);
						if(isset($row['catid'])){
								$row['category'] = model('Category')->getCategoryByCache($row['catid']);
						}
						$this->view->assign("schoolid",$schoolid);
						$this->view->assign("row", $row);
						return $this->view->fetch();
				}
		}
		public function index(){
				$columnlist = Cols::columnread('classes');
				$searchfileds = array();$searchdefault = array();
				$flag = array();$options = array();
				foreach($columnlist as $v){
						$flag[] = $v['listorder'];
						if($v['options']){
								//把带有选项的列，提取出来。
								$options[$v['columnenname']] = $v['options'];
						}
						if($v['isshowsearch']){
								$searchfileds[$v['columnenname']] = $v['columntype'];
						}
				}
				array_multisort($flag, SORT_ASC, $columnlist);
				//设置过滤方法
				$this->request->filter(['strip_tags']);
				//如果发送的来源是Selectpage，则转发到Selectpage
				if ($this->request->request('pkey_name')){
						return $this->selectpage();
				}
				$searchdefault['schoolid'] = '0';
				list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds,null,$searchdefault);
				$order = 'desc';
				$sort = 'itemid';
				$total = $this->model
				->where($where)
				->order($sort, $order)
				->count();
				$totalpage = 1;$page = 1;
				if($limit>0){
						$totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
						//总页数
						if($offset>0){$page = intval($offset/$limit)+1;}
				}
				$list = $this->model
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
				for ($i = 0; $i < count($list); $i++) {
						if(isset($list[$i]['catid'])){
								$catarry = model('Category')->getCategoryByCache($list[$i]['catid']);
								$list[$i]['categoryname'] = $catarry['name'];
								$list[$i]['categorydiyname'] = $catarry['diyname'];
						}
						unset($list[$i]['intro']);unset($list[$i]['content']);
						foreach ($options as $k => $v) {
								if(isset($list[$i][$k])){
										$arj = json_decode($v,true);
										$sarj = isset($arj[$list[$i][$k]])?$arj[$list[$i][$k]]:"";
										$list[$i][$k] = $sarj;
								}
						}
												if(cache('school'.$list[$i]['itemid'])!==null){
								$datacache = cache('school'.$list[$i]['schoolid']);
								$list[$i]['schooladdress'] = $datacache['address'];
						}
						if(cache('school'.$list[$i]['itemid'])!==null){
								$datacache = cache('school'.$list[$i]['schoolid']);
								$list[$i]['schoolname'] = $datacache['name'];
						}

				}
				$result = array("total" => $total, "rows" => $list);
				$this->view->assign("lists",$result['rows']);
				$this->view->assign("listsjson",json_encode($result['rows']));
				$this->view->assign("columnlistjson",json_encode($columnlist));
				$this->view->assign("columnlist",$columnlist);
				$this->view->assign("total",$result['total']);
				$this->view->assign("offset",$offset);
				$this->view->assign("limit",$limit);
				$this->view->assign("totalpage",$totalpage);
				$this->view->assign("page",$page);
				return $this->view->fetch('index');
		}
		public function select(){
				$columnlist = Cols::columnread('classes');
				$flag = array();$options = array();
						foreach($columnlist as $v){
								$flag[] = $v['listorder'];
								if($v['options']){
										//把带有选项的列，提取出来。
										$options[$v['columnenname']] = $v['options'];
								}
						}
				array_multisort($flag, SORT_ASC, $columnlist);
				//设置过滤方法
				$this->request->filter(['strip_tags']);
				//如果发送的来源是Selectpage，则转发到Selectpage
				if ($this->request->request('pkey_name')){
						return $this->selectpage();
				}
				$searchfileds = array();$searchdefault = array();
				$searchfileds['name'] = 'varcharshort';
				$searchfileds['schoolid'] = 'bigint';
				list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds,null,$searchdefault);
				$order = 'desc';
				$sort = 'itemid';
				$total = $this->model
				->where($where)
				->order($sort, $order)
				->count();
				$totalpage = 1;$page = 1;
				if($limit>0){
						$totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
						//总页数
						if($offset>0){$page = intval($offset/$limit)+1;}
				}
				$list = $this->model
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
				for ($i = 0; $i < count($list); $i++) {
						if(isset($list[$i]['catid'])){
								$catarry = model('Category')->getCategoryByCache($list[$i]['catid']);
								$list[$i]['categoryname'] = $catarry['name'];
								$list[$i]['categorydiyname'] = $catarry['diyname'];
						}
						unset($list[$i]['intro']);unset($list[$i]['content']);
						foreach ($options as $k => $v) {
								if(isset($list[$i][$k])){
										$arj = json_decode($v,true);
										$sarj = isset($arj[$list[$i][$k]])?$arj[$list[$i][$k]]:"";
										$list[$i][$k] = $sarj;
								}
						}
												if(cache('school'.$list[$i]['itemid'])!==null){
								$datacache = cache('school'.$list[$i]['schoolid']);
								$list[$i]['schooladdress'] = $datacache['address'];
						}
						if(cache('school'.$list[$i]['itemid'])!==null){
								$datacache = cache('school'.$list[$i]['schoolid']);
								$list[$i]['schoolname'] = $datacache['name'];
						}

				}
				$result = array("total" => $total, "rows" => $list);
				$this->view->assign("lists",$result['rows']);
				$this->view->assign("listsjson",json_encode($result['rows']));
				$this->view->assign("columnlistjson",json_encode($columnlist));
				$this->view->assign("columnlist",$columnlist);
				$this->view->assign("total",$result['total']);
				$this->view->assign("offset",$offset);
				$this->view->assign("limit",$limit);
				$this->view->assign("totalpage",$totalpage);
				$this->view->assign("page",$page);
				$this->view->assign("multiple",$this->request->get('multiple'));
				return $this->view->fetch();
		}
		/**
		* 删除
		*/
		public function del($ids = ""){
				if($ids){
						$model = $this->model->get($ids);
						$model->delete();
				}
				$this->error(__('Parameter %s can not be empty', 'ids'));
		}
		/**
		* 删除类别
		* @internal
		*/
		public function dels(){
				if ($this->request->isPost()){
						$ids = $this->request->post("ids");
						$idarry = explode(',', $ids);
						foreach ($idarry as $k => $v) {
								if($v){
										$model = $this->model->get($v);
										$model->delete();
								}
						}
						$this->success();
						exit;
				}
				$this->error(__('Parameter %s can not be empty', 'ids'));
		}
		public function showlist(){
				$ids = $this->request->post('ids');
				$ischeck = $this->request->post('ischeck');
				model('Column')->where('itemid',$ids)->update(['isshowlist'=>($ischeck==='true'?1:0)]);
				$ll = model('Column')->getColumnsByModel('classes');
				$lls = array();
				foreach ($ll as $k => $v) {
						$lls[ucfirst($v['columnenname'])] = $v;
				}
				$string = "<?php return ".var_export($lls, true)."; ?>";
				$filename = COLUMN_PATH.DS.'classes.php';
				$result = file_put_contents($filename, $string);
				if(@$fp = fopen($filename,'wb')) {
						flock($fp, LOCK_EX);
						$len = fwrite($fp, $string);
						flock($fp, LOCK_UN);
						fclose($fp);
						echo $len;exit;
				} else {
						echo '失败了';exit;
				}
		}
		/**
		* 数据列表返回json数据
		*/
		public function ajaxlist(){
				$ll = array();$llary = array();$arrwhere = array();$returnarry = array();
				if($this->request->get('tree')){
						$llv = collection(model('classes')->where($arrwhere)->order('createtime', 'desc')->select())->toArray();
						Tree::instance()->init($llv);
						$ll = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(''), 'name');
				}else{
						$ll = collection(model('classes')->where($arrwhere)->order('createtime','desc')->select())->toArray();
				}
				for ($i=0; $i < count($ll); $i++) {
						if($ll[$i]['itemid']==$this->request->get('currentid')){
								$ll[$i]['selected'] = 1;
						}else{
								$ll[$i]['selected'] = 0;
						}
				}
				if(count($ll)>0){
						print_r(json_encode($ll));exit;
				}else{
						print_r(json_encode($ll));exit;
				}
		}
}
?>
